package com.lingfengerick.commons.encrypt;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author lingfengerick
 * @since 2021/8/9 10:00 下午
 */
public class Md5Utils {

    private static final String[] HEX_DIGITS = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
    *
    * @author  lingfengerick
    * @since 2021/8/10  11:15 下午
    * @param bytes 字节
    * @return 转义后的串
    *
    */
    private static String byteArrayToHexString(byte bytes[]) {
        StringBuilder resultSb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++){
            resultSb.append(byteToHexString(bytes[i]));
        }
        return resultSb.toString();
    }

    /**
    *
    * @author  lingfengerick
    * @since 2021/8/10  11:17 下午
    * @param byteParam 字节
    * @return 转义后的字符串
    *
    */
    private static String byteToHexString(byte byteParam) {
        int n = byteParam;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    /**
    *
    * @author  lingfengerick
    * @since 2021/8/10  11:16 下午
    * @param origin 要加密的数据
    * @param charset 字符编码
    * @return 加密后的字符
    * @throws UnsupportedEncodingException 异常
    * @throws NoSuchAlgorithmException 异常
    */
    public static String MD5Encode(String origin, String charset) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String resultString = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (StringUtils.isEmpty(charset)) {
                resultString = byteArrayToHexString(md.digest(origin.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(origin.getBytes(charset)));
            }
        } catch (Exception e) {
            throw e;
        }
        return resultString;
    }
}
